package org.jiucheng.magpiebridge.server.aio.proxy;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.protocol.Message;
import org.jiucheng.magpiebridge.server.aio.ServerAttachment;
import org.jiucheng.magpiebridge.server.aio.ServerWriteNoProxyClientReadCompletionHandler;
import org.jiucheng.magpiebridge.server.util.Container;

/**
 * 
 * @author jiucheng
 *
 */
public class ProxyEstablishmentCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, ProxyEstablishmentAttachment> {
    
    public void completed(AsynchronousSocketChannel result, ProxyEstablishmentAttachment attachment) {
        attachment.getProxy().accept(attachment, this);
        
        if (attachment.getServerAttachment().canWrited()) {
            Message message = new Message();
            message.setMagic(Message.MAGIC);
            message.setType(Message.Type.CONNECT);
            message.setUri(Container.CLIENTS_ID.incrementAndGet());
            byte[] data = attachment.getRemote().getBytes();
            message.setData(data);
            message.setSize(data.length);
            ByteBuffer writeBuffer = Message.toByteBuffer(message);
            
            ServerAttachment.proxys.put(message.getUri(), new ProxyAttachment(result).setUri(message.getUri()).setServerAttachment(attachment.getServerAttachment()));
	        attachment.getServerAttachment().getServer().write(writeBuffer, attachment.getServerAttachment().setWriteBuffer(writeBuffer), new ServerWriteNoProxyClientReadCompletionHandler());
        }
    }

    public void failed(Throwable exc, ProxyEstablishmentAttachment attachment) {
        attachment.getServerAttachment().writed.compareAndSet(true, false);
        exc.printStackTrace();
        System.out.println("proxy server failed");
    }
}
